package com.wqy.netty.oio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Hello world!
 *
 */
public class IoServeer
{
    public static void main( String[] args ) throws IOException {
        ServerSocket serverSocket = new ServerSocket(10010);
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        System.out.println("服务启动");
        while (true){
            final Socket socket = serverSocket.accept();
            System.out.println("来了个新客户端");
            newCachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    handle(socket);
                }
            });

        }
    }

    private static void handle(Socket socket) {
        InputStream inputStream = null;
        try {
            byte[] bytes = new byte[1024];
            inputStream = socket.getInputStream();
            while (true){
                int read = inputStream.read(bytes);
                if (read != -1){
                    System.out.print(new String(bytes));
                }else{
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                socket.close();
                if (inputStream != null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
